<?php

namespace app\admin\quick\actions;


use quick\admin\actions\RowAction;
use quick\admin\annotation\AdminAuth;
use quick\admin\components\Component;
use quick\admin\form\Form;
use quick\admin\http\model\Model;
use quick\admin\http\response\JsonResponse;
use quick\admin\library\service\PluginService;
use quick\admin\library\service\QueueService;
use think\facade\Db;
use think\Request;

/**
 * 插件设置
 * @AdminAuth(title="插件设置",auth=true,menu=true,login=true)
 * @package app\admin\resource\example\actions
 */
class PluginConfigAction extends RowAction
{

    /**
     * 模型主键
     *
     * @var string
     */
    public static $pk = "name";

    /**
     * 关联模型
     *
     * @var string
     */
    protected static $model = 'app\common\model\SystemPlugin';


    /**
     * 动作提交数据接口
     *
     * @return mixed
     * @throws \quick\admin\Exception
     * @throws \think\Exception
     */
    public function store()
    {
        $model = $this->findModel();
        if (!$model) {
            quick_abort(500, '资源不存在');
        }

        return $this->handle($model, $this->request);
    }

    /**
     * @param $request
     * @param $model
     * @return \quick\admin\http\response\JsonResponse
     */
    protected function resolve($request, $model)
    {


    }

    /**
     * 动作异步数据接口
     * @return mixed
     * @throws \quick\admin\Exception
     * @throws \think\Exception
     */
    public function load()
    {
        $model = $this->findModel();
        if (!$model) {
            quick_abort(500, '资源不存在');
        }
        $pluginInfo = pluginInfo($model['name']);
        $model['is_config'] = $pluginInfo['is_config'];
        if (!$this->handleCanRun($this->request, $model)) {
            quick_abort(500, '你无权访问');
        }

        if ($this->beforeLoadCallback instanceof \Closure) {
            $beforeSavingCallback = \Closure::bind($this->beforeLoadCallback,$this);
            $model = call_user_func($beforeSavingCallback, $model, $this->request);
        }



        $configService = $this->getConfigService($model['name']);
        $form = $configService->form();
        $form->fixedFooter();
        $form->hideReset();
        $form->url($this->storeUrl([
            self::$keyName => $this->request->param(self::$keyName)
        ]));
        $form->resolve(json_decode($model->config,true));
        $form->style("background-color", '#FFFFFF');
        $form = $this->resolveComponent($form);
        return $this->response()->success('success', $form);
    }


    protected function getConfigService(string $pluginName)
    {
        $plugin = plugin($pluginName);
        return $plugin->configForm();
    }



    protected function handle($model, $request)
    {

        $configService = $this->getConfigService($model['name']);
        $form = $configService->form();

        $data = (array)$form->getSubmitData($this->request, 3);
        Db::startTrans();
        try {

            $data = $configService->beforeSave($data, $request);

            $model->config = json_encode($data);

            /** @var Model $model */
            $res = $model->save();
            if (!$res) {
                throw new \Exception("设置失败：".$model->getFirstError());
            }

            $res = $configService->afterSave($data, $request);
            if ($res === false) {
                throw new \Exception("设置失败");
            }

            if ($res instanceof JsonResponse) {
                $response = $res;
            } else {
                $response = $this->response()->success("设置成功");
            }

            if ($this->isPage()) {
                $response->push($this->backUrl("index"));
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $response = $this->response()->error($e->getMessage());
        }

        return $response;
    }


}
